extends Node

var player_scene = load("res://scene/player.tscn")

func _ready() -> void:
	if multiplayer.is_server():
		_add_server_player()
	
	multiplayer.peer_connected.connect(_add_client_player)
	multiplayer.peer_disconnected.connect(_peer_disconnected_info)

func _add_server_player() -> void:
	var player = player_scene.instantiate()
	player.name = '1'
	player.position = $Marker2D.position
	player.modulate = 'fc3dff'
	call_deferred("add_child", player)
	print('服务器玩家：id->', multiplayer.get_unique_id())

func _add_client_player(id: int) -> void:
	var player = player_scene.instantiate()
	player.name = str(id)
	player.position = $Marker2D.position
	#随机颜色
	var random = RandomNumberGenerator.new()
	if random.randi_range(1, 2) == 1:
		player.Modulate = 'ffff3d'
	else:
		player.Modulate = '3db5ff'
	call_deferred("add_child", player)
	print('客户端玩家加入:id->', player.name)

func _peer_disconnected_info(id: int) -> void:
	print('客户端玩家离开:id->', id)
	get_node(str(id)).queue_free()
